package com.k.kc.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

/**
 * @author k
 */
public class PingUtils {
    private static final String PINT_RESPONSE_SYMBOL = "TTL";

    public static boolean ping(String ipAddress) {
        // 超时应该在3钞以上
        int timeOut = 3000;
        // 当返回值是true时，说明host是可用的，false则不可。
        try {
            return InetAddress.getByName(ipAddress).isReachable(timeOut);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param ipAddress  ip地址
     * @param pingTimes  次数(一次ping,对方返回的ping的结果的次数)
     * @param timeOut    超时时间 单位ms(ping不通,设置的此次ping结束时间)
     * @return R
     */
    public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
        BufferedReader in = null;
        String pingCommand;
        Runtime r = Runtime.getRuntime();
        String osName = System.getProperty("os.name");
        System.out.println("项目所在系统是:" +osName);
        if(osName.contains("Windows")){
            //将要执行的ping命令,此命令是windows格式的命令
            pingCommand = "ping " + ipAddress + " -n " + pingTimes    + " -w " + timeOut;
        }else{
            //将要执行的ping命令,此命令是Linux格式的命令
            //-c:次数,-w:超时时间(单位/ms)  ping -c 10 -w 0.5 192.168.120.206
            pingCommand = "ping " + " -c " + "4" + " -w " + "2 " + ipAddress;
        }
        try {
            //执行命令并获取输出
            Process p = r.exec(pingCommand);
            if (p == null) {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            int connectedCount = 0;
            String line;
            while ((line = in.readLine()) != null) {
                connectedCount += getCheckResult(line);
            }
            //如果出现类似=23 ms ttl=64(TTL=64 Windows)这样的字样,出现的次数=测试次数则返回真
            //return connectedCount == pingTimes;
            System.out.println("ping通设备IP的次数为:" +connectedCount);
            return connectedCount >= 2;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 若line含有=18 ms ttl=64字样,说明已经ping通,返回1,否則返回0.
     * @param line line
     * @return R
     */
    private static int getCheckResult(String line) {
        return line.toUpperCase().contains(PINT_RESPONSE_SYMBOL)?1:0;
    }

    public static void main(String[] args) {
        String ipAddress = "10.161.64.87";
        System.out.println(ping(ipAddress,3,3000));
        //System.out.println(ping(ipAddress));
    }
}
